import grpc
import time
from   concurrent import futures
import stream_pb2 
import stream_pb2_grpc

ONE_DAY_IN_SECONDS = 24 * 60 * 60

class GreetService(stream_pb2_grpc.GreetingServicer):
    def SayGreeting(self, request, context):
        """Unary方法 SayGeeting

        Args:
            request (客户端请求消息 GreetRequest): 用户请求的输入数据结构
            context (上下文): [description]

        Returns:
            [GreetResponse]: 服务端返回客户端的消息
        """
        # metadata = dict(context.invocation_metadata()) 
        # print(metadata)    {'user-agent': 'grpc-python/1.62.1 grpc-c/39.0.0 (linux; chttp2)'}
        words = request.greet_word
        users = request.user
        users_list = ", ".join([user.name for user in users])
        print(f"Received: \n {words} from {users_list}")
        return stream_pb2.GreetResponse(response=f"Received yours message {words} from {users_list}")
        
    
    def MultiGreeting(self, request_iterator, context):
        """多个请求合并到一起返回

        Args:
            request_iterator ([type]): [description]
            context ([type]): [description]

        Returns:
            [type]: [description]
        """
        namelist = ""
        for req in request_iterator:
            users = req.user 
            namelist = namelist + ", ".join([user.name for user in users ])+","
        print(f"receved greetings from {namelist}")
        return stream_pb2.GreetResponse(response=f"receved greetings from {namelist}" )

    def MultiGreetingResp(self, request, context):
        g_word = request.greet_word
        users = request.user
        namelist = ", ".join([user.name for user in users ])
        print(f"receved: \n {g_word} from {namelist}")    
        
        # 使用迭代器进行流式返回
        for user in users:
            yield stream_pb2.GreetResponse(response=f"Hello, {user.name}, thank you for greeting" )
            

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4))
    
    stream_pb2_grpc.add_GreetingServicer_to_server(GreetService(), server)
    server.add_insecure_port("[::]:8888")
    server.start()
    print("Server started, listening on port: 8888")
    # server.wait_for_termination()
    
    try:
        while True:
            print("===============sleeping====================")
            time.sleep(ONE_DAY_IN_SECONDS)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == "__main__":
    serve()
